const router = require('koa-router')()
const {isExist, register, login, changePassword, logout, isLogin, getUsers} = require('../../controller/user')
const userValidate = require('../../validator/user')
const {genValidator} = require('../../middlewares/validator')
const {loginCheck} = require('../../middlewares/loginChecks')

router.prefix('/api/user')

router.get('/user', async (ctx, next) => {
  const {userName, nickName, pageIndex, pageSize} = ctx.query
  const createTime = ctx.query['createTime[]']
  ctx.body = await getUsers({userName, nickName, pageIndex, pageSize, createTime})
})

router.post('/register', genValidator(userValidate), async (ctx, next) => {
  const {userName, password, nickName} = ctx.request.body
  ctx.body = await register({userName, password, nickName})
})

router.post('/isExist', async (ctx, next) => {
  const {userName} = ctx.request.body
  ctx.body = await isExist(userName)
})

router.post('/login', genValidator(userValidate), async (ctx, next) => {
  const {userName, password} = ctx.request.body
  ctx.body = await login(ctx, userName, password)
})

router.patch('/changePassword', loginCheck, genValidator(userValidate), async (ctx, next) => {
  const {password, newPassword} = ctx.request.body
  ctx.body = await changePassword(ctx, {password, newPassword})
})

router.post('/logout', loginCheck, async (ctx, next) => {
  ctx.body = await logout(ctx)
})

router.post('/isLogin', async (ctx, next) => {
  ctx.body = await isLogin(ctx)
})

module.exports = router
